package com.cloud.example.config.tx;

import com.cloud.async.flow.web.tx.TransactionSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * MyBatis事务配置:测试通过
 * @author chengr
 */
public class MybatisTransactionSourceFlow implements TransactionSource {


    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    TransactionDefinition transactionDefinition;


    @Override
    public boolean commitTrans(Object transactionObj) {
        TransactionStatus transaction = (TransactionStatus) transactionObj;
        dataSourceTransactionManager.commit(transaction);
        return true;
    }

    @Override
    public boolean rollBack(Object transactionObj) {
        TransactionStatus transaction = (TransactionStatus) transactionObj;
        dataSourceTransactionManager.rollback(transaction);
        return true;
    }


    @Override
    public TransactionStatus newSession(){
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(def);
        //TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        return transactionStatus;
    }

}
